package service

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
	"wechat_1004/internal/model"
	"wechat_1004/internal/params"
)

type Nide struct {
	Conn *websocket.Conn
	Data chan []byte
}

var Client map[int32]*Nide = make(map[int32]*Nide)

func Chat(c *gin.Context) {
	var req params.ChatForm

	var upgrader = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	}
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Println(err)
		return
	}

	Client[req.UserId] = &Nide{
		Conn: conn,
		Data: make(chan []byte),
	}

	go ReadMessage(Client[req.UserId])
	go WriteMessage(Client[req.UserId])

}

func ReadMessage(nide *Nide) {
	for {
		_, message, err := nide.Conn.ReadMessage()
		if err != nil {
			return
		}

		var req params.ChatForm

		json.Unmarshal(message, &req)

		messageTo := Client[req.FriendId].Data
		messageTo <- message

	}
}

func WriteMessage(nide *Nide) {
	for {
		data := <-nide.Data

		nide.Conn.WriteMessage(websocket.TextMessage, data)

	}
}

func FindMessageChat(c *gin.Context) {
	var req params.FindMessageChatForm

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    100000,
			"message": "验证失败",
			"data":    "",
		})
		return
	}

	var message model.Message
	message.UserId = req.UserId
	message.FriendId = req.FriendId
	findMessage, err := message.FindMessage()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    100000,
			"message": "查看失败",
			"data":    err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "查看成功",
		"data":    findMessage,
	})
}
